<template>
  <div class="scan-login">
    <div class="title mt10">扫码登录</div>
    <img class="mt20" :src="scanImg" alt="">
    <p class="mt20">使用<span>网易云音乐App</span>扫码登录</p>
  </div>
</template>

<script setup>
import {onMounted,ref,onUnmounted,getCurrentInstance} from 'vue'
import {useUserStore} from '@/store/userInfo'
const userStore=useUserStore()
const props=defineProps({
  getScanLoginShow:{
    type:Function
  }
})
import axios from 'axios'
const {proxy}=getCurrentInstance()
let scanImg=ref('')
/**
 * 登录
 */
// 1. 获取二维码id
let getScanId=async()=>{
  const {data}=await proxy.$api.getScanId()
  return data.unikey
}
// 2. 生成二维码图片
let proScanImg=async(key)=>{
  const {data}=await proxy.$api.proScanImg({key,qrimg:true})
  scanImg.value=data.qrimg
}
// 3. 检测扫码状态
let checkState=async(key)=>{
  const data=await proxy.$api.checkState({key})
  return data
}
/**
 * 获取用户相关信息
 */

// 1. 获取登录状态保存uid
let getLoginState=async(cookie)=>{
  let res=await proxy.$api.loginState({cookie})
  const uid=res.data.profile.userId
  userStore.saveUid(uid)
}
// 2. 获取用户关注列表
let userFollows=async()=>{
  let {follow}=await proxy.$api.userFollows({uid:userStore.uid})
  console.log(userStore.uid);
  userStore.saveUserInfo('follow',follow)
}
// 3. 获取用户粉丝列表
let userFolloweds=async()=>{
  let {followeds}=await proxy.$api.userFolloweds({uid:userStore.uid})
  userStore.saveUserInfo('followeds',followeds)
}
// 3. 获取用户等级
let userLeave=async()=>{
  let {data}=await proxy.$api.userLeave({uid:userStore.uid})
  userStore.saveUserInfo('leave',data.leave)
}
// 4. 获取用户详情
let userDetail=async()=>{
  let {code,...data}=await proxy.$api.userDetail({uid:userStore.uid})
  userStore.saveUserInfo('detail',data)
}
// 5. 获取用户歌单
let getuserPlayList=(async()=>{
  let {playlist}=await proxy.$api.getuserPlayList({uid:userStore.uid})
  userStore.saveplayList(playlist)
})
let timer
onMounted(async()=>{
  const unikey=await getScanId()
  proScanImg(unikey)
  timer=setInterval(async()=>{
    const {code,cookie,message}=await checkState(unikey)
    console.log(code,cookie,message);
    if(code===800){
      proxy.$message({
        type:'error',
        message
      })
      clearInterval(timer)
      proxy.$router.go(0)
    }
    if(code===803){
      clearInterval(timer)
      proxy.$message({
        type:'success',
        message
      })
      // 保存cookie
      await userStore.saveCookie(cookie)
      // 保存uid
      await getLoginState(cookie)
      await userFollows()
      await userFolloweds()
      await userLeave()
      await userDetail()
      await getuserPlayList()
      userStore.setShowUserInfo(true)
      props.getScanLoginShow(false)
    }
  },3000)
  
})
onUnmounted(()=>{
  clearInterval(timer)
})
</script>

<style lang="scss">
.scan-login{
  height: 100%;
  text-align: center;
  .title{
    font-size: 32px;
  }
  p{
    span{
      color:#0ea5e9;
    }
  }
}
</style>